﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;

namespace RS232_WPF
{
    /// <summary>
    /// MainWindow.xaml 的交互逻辑
    /// </summary>
    public partial class MainWindow : Window
    {
        public MainWindow()
        {
            InitializeComponent();
            sjw.SelectedIndex = 0;
            tzw.SelectedIndex = 0;
            btl.SelectedIndex = 0;
            jyw.SelectedIndex = 0;
        }
        RS232Helper rS232Helper = new RS232Helper();
        private void Button_Click(object sender, RoutedEventArgs e)
        {
            if (BtnOpen.Content.ToString() == "打开串口")
            {
                SetProt();
                if (rS232Helper.sp.IsOpen)
                {
                    com.IsReadOnly = false;
                    btl.IsReadOnly = false;
                    sjw.IsReadOnly = false;
                    tzw.IsReadOnly = false;
                    BtnOpen.Content = "关闭串口";
                    Log.Text += DateTime.Now + " 串口开启成功:" + "\n";
                }
                else
                {
                    try
                    {
                        rS232Helper.sp.Open();
                        com.IsReadOnly = true;
                        btl.IsReadOnly = true;
                        sjw.IsReadOnly = true;
                        tzw.IsReadOnly = true;

                        BtnOpen.Content = "关闭串口";
                        Log.Text += DateTime.Now + " 串口开启成功:" + "\n";
                    }
                    catch (Exception ex)
                    {
                        MessageBox.Show("串口打开失败,失败原因：" + ex.Message, "错误提示");
                        Log.Text += "串口打开失败,失败原因：" + ex.Message;
                    }
                }
            }
            else //关闭串口
            {
                if (rS232Helper.sp.IsOpen) //判断串口是否打开
                {
                    try
                    {
                        rS232Helper.sp.Close(); //关闭串口
                        rS232Helper.ShowData -= ShowData;
                       //启用设置控件

                       Log.Text += "串口关闭成功！";
                        BtnOpen.Content = "打开串口";
                    }
                    catch (Exception ex)
                    {
                        MessageBox.Show("串口关闭失败,错误提示：" + ex.Message, "错误提示");
                        Log.Text += "串口关闭失败,错误提示：" + ex.Message;
                    }
                }
                else
                {

                    BtnOpen.Content = "打开串口";
                    Log.Text += "串口未打开，无法关闭！";
                    MessageBox.Show("串口未打开，无法关闭！", "错误提示");
                }
            }

        }
        private void SetProt()
        {
            string result = rS232Helper.SetPortProperty(com.SelectionBoxItem.ToString(), btl.SelectionBoxItem.ToString(), tzw.SelectionBoxItem.ToString(), sjw.SelectionBoxItem.ToString(), jyw.SelectionBoxItem.ToString(), false);
            rS232Helper.ShowData += ShowData;
            if (!string.IsNullOrEmpty(result))
            {
                Log.Text += result + "\n";
            }

        }
        private void ShowData(string obj)
        {
            App.Current.Dispatcher.Invoke(() =>
            {
                try{
                    Log.Text += DateTime.Now + " 收到数据:" + obj + "\n";
                    if (!string.IsNullOrEmpty(obj))
                    {
                        string[] strlist = obj.Split(',');
                        if (strlist.Length >= 2)
                            xh.Text = strlist[2];
                        Log.Text += DateTime.Now + " 数据长度:" + strlist.Length + "\n";
                    }
                    SendMessage();
                    Log.Text += DateTime.Now + " 自动回写信号:" + sendInfo.Text + "\n";
                }
                catch(Exception ex)
                {
                    Log.Text += DateTime.Now + " 获取数据异常:" + ex.Message + "\n";
                }
            }
                );
        }

        private void Button_Click_1(object sender, RoutedEventArgs e)
        {
            List<string> comlist = rS232Helper.CheckPort();
            if (comlist.Count > 0)
            {
                foreach (var item in comlist)
                {
                    com.Items.Add(item);
                }
                com.SelectedIndex = 0;
            }
            else
            {
                for (int i = 1; i < 5; i++)
                {
                    com.Items.Add("COM" + i);
                }

            }

        }

        private void Button_Click_2(object sender, RoutedEventArgs e)
        {
            SendMessage();
        }

        public void SendMessage()
        {
            try
            {
                string mystr1 = sendInfo.Text;
                if (rS232Helper.isHex)
                {
                    mystr1 = rS232Helper.HexToASCII(sendInfo.Text);
                }
                byte[] a = Encoding.UTF8.GetBytes(mystr1);
                string mystr2 = Encoding.UTF8.GetString(a);
                rS232Helper.sp.Write(mystr2);//将数据写入串行端口输出缓冲区
                // tbxReceivedData.Text += tbxSendData.Text + "\r\n";
                Log.Text += mystr2 + "发送成功！" + "\r\n";
            }
            catch
            {
                Log.Text = sendInfo.Text + "发送失败" + "\r\n";
            }
        }
    }
}
